package chat

import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintStream
import java.net.Socket
import java.util.*

//可以允许有多个客户端

fun main(args : Array<String>){


    val client = Client("127.0.0.1", 9999)          //注册一个客户端

        println("请输入您的名字: ")
    val `in` = BufferedReader(InputStreamReader(System.`in`))
    val username = `in`.readLine()          //保存名字

    client.connect(username)        //该用户进行连接

    while(client.connected == null){ }    //直到连接成功

    while (client.connected!!) {
        val reader = BufferedReader(InputStreamReader(System.`in`))
        val message = reader.readLine()         //读消息
        client.sendMessage(message)     //发送
        //println("客户端测试")
    }
}

class Client (val host:String, val port : Int){

    var readClient : Socket? = null //
    var writeClient : Socket? = null //

    var username : String? = null
        private set

    var connected : Boolean? = null
        private set

    fun connect(username : String){
        this.username = username

        readClient = Socket(host, port)   //使用socket
        val out = PrintStream(readClient?.outputStream)

        out.println(username)   //像服务端发送用户名

        //客户端输入接收器
        val s = Scanner(readClient?.inputStream)

        //
        while(!s.hasNextLine()){}

        val response = s.nextLine()     //服务端返回一个int值，端口号
        //println(response.toInt())

        if (response.length > 5) { //
            println("用户名已用，服务器拒绝连接")
            readClient?.close()
            connected = false
        }else{ //
            //开启新的线程，接收消息
            Thread(MessageReceiver(readClient!!.inputStream)).start()

            writeClient = Socket(host, response.toInt())    //这个Socket第二个参数？
            connected = true
        }
    }

    /**
     * 发送消息
     */
    fun sendMessage(message: String) {
        PrintStream(writeClient?.outputStream)
                .println(Message(username!!, message))
    }

    /**
     * 接收消息
     */
    class MessageReceiver (val server : InputStream): Runnable {
        override fun run() {
            val s = Scanner(server)
            while(s.hasNextLine()){                 //Message有固定的消息格式，在
                val message = Message.Companion.parseMessage(s.nextLine())
                println("${message.usernameFrom} 消息: ${message.text}")
            }
        }
    }

}